package com.example.user_center.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.user_center.common.ErrorCode;
import com.example.user_center.exception.BusinessException;
import com.example.user_center.pojo.User;
import com.example.user_center.pojo.request.UserRegisterRequest;
import com.example.user_center.service.UserService;
import com.example.user_center.mapper.UserMapper;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.example.user_center.contant.UserContent.USER_LOGIN_STATE;

/**
* @author 22948
* @description 针对表【user(用户表)】的数据库操作Service实现
* @createDate 2025-03-04 09:09:11
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    @Autowired
    private UserMapper userMapper;

    private final static String SALT = "fld";

    @Override
    public long userRegister(UserRegisterRequest userRegisterRequest) {

        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String planetCode = userRegisterRequest.getPlanetCode();
        // 1.校验 非空
        if (StringUtils.isBlank(userAccount) || StringUtils.isBlank(userPassword) || StringUtils.isBlank(checkPassword) || StringUtils.isBlank(planetCode)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空...");
        }

        // 2. 账户长度不小于四位
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户长度小于四位");
        }

        // 3.密码长度不小于8位
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码长度小于8位");
        }

        // 5.账户不包括特殊字符
        String validPattern = "[^\\w\\s]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户包括了特殊字符...");
        }

        // 6.密码和校验码要相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码和校验码不一致...");
        }

        // 星球编码校验
        if (planetCode.length() > 5) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"星球编码过长...");
        }

        // 4.账户不能重复 (调用数据库) 用到plus的方法
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("userAccount",userAccount);
        long count = userMapper.selectCount(userQueryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户重复...");
        }

        // 4.星球编号不能重复 (调用数据库) 用到plus的方法
        userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("planetCode",planetCode);
        count = userMapper.selectCount(userQueryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"星球编码重复...");
        }

        // 7. 密码加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

        // 8. 向数据库中插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setPlanetCode(planetCode);
        boolean save = this.save(user);

        if (!save) {
            throw new BusinessException(ErrorCode.NULL_ERROR,"数据为空, 数据库插入失败...");
        }

        return user.getId();
    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {

        // 1.校验 非空
        if (StringUtils.isBlank(userAccount) || StringUtils.isBlank(userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空...");
        }

        // 2. 账户长度不小于四位
        if (userAccount .length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户长度小于四位...");
        }

        // 3.密码长度不小于8位
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码长度小于8位...");
        }

        // 5.账户不包括特殊字符
        String validPattern = "[^\\w\\s]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户包含了特殊字符...");
        }

        // 对密码加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

        // 在数据库中查询是否存在该用户
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("userAccount",userAccount);
        userQueryWrapper.eq("userPassword",encryptPassword);
        User user = userMapper.selectOne(userQueryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("该用户不存在...");
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户不存在...");
        }

        // 用户脱敏
        User safetyUser = getSafetyUser(user);

        // 获得session 将脱敏之后的用户传入session并返回给前端
        request.getSession().setAttribute(USER_LOGIN_STATE,safetyUser);

        return safetyUser;
    }

    @Override
    public User getSafetyUser(User user) {
        // 如果拿到的数据是空的 不判断直接去调用user的方法 会报空指针异常。
        if (user == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR,"user对象为空...");
        }
        //用户脱敏 (就是用户的个人私密信息不能直接被前端接收到和看到)
        User safetyUser = new User();
        safetyUser.setId(user.getId());
        safetyUser.setUsername(user.getUsername());
        safetyUser.setUserAccount(user.getUserAccount());
        safetyUser.setAvatarUrl(user.getAvatarUrl());
        safetyUser.setGender(user.getGender());
        safetyUser.setPhone(user.getPhone());
        safetyUser.setEmail(user.getEmail());
        safetyUser.setUserStatus(user.getUserStatus());
        safetyUser.setCreateTime(user.getCreateTime());
        safetyUser.setUserRole(user.getUserRole());
        safetyUser.setPlanetCode(user.getPlanetCode());
        return safetyUser;
    }

    @Override
    public Integer userLogout(HttpServletRequest request) {

        if (request == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR,"请求参数为空...");
        }
        // 直接移除用户登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);

        return 1;
    }
}




